//
//  DMTMD360PlayViewController.m
//  DMT_VR
//
//  Created by xin on 2016/10/21.
//  Copyright © 2016年 Elephant-Parade. All rights reserved.
//

#import "DMTMD360PlayViewController.h"
#import "VIMVideoPlayerView.h"
#import "VIMVideoPlayer.h"
#import "MDVRLibrary.h"
#import <ReactiveObjC/ReactiveObjC.h>

#define RGBCOLOR_HEX(hexColor) [UIColor colorWithRed: (((hexColor >> 16) & 0xFF))/255.0f         \
green: (((hexColor >> 8) & 0xFF))/255.0f          \
blue: ((hexColor & 0xFF))/255.0f                 \
alpha: 1]

@interface CustomDirectorFactory : NSObject<MD360DirectorFactory>

@end

@implementation CustomDirectorFactory

- (MD360Director*) createDirector:(int) index{
    MD360Director* director = [[MD360Director alloc]init];
    switch (index) {
        case 1:
            [director setEyeX:-2.0f];
            [director setLookX:-2.0f];
            break;
        default:
            break;
    }
    return director;
}

@end

@interface DMTMD360PlayViewController () <VIMVideoPlayerDelegate>
{
    BOOL isShowToolBar;
}
@property (nonatomic, strong) VIMVideoPlayer *player;
@property (nonatomic, strong) AVPlayer *avPlayer;
@property (nonatomic, strong) MDVRLibrary* vrLibrary;
@property (assign, nonatomic) BOOL isScrubbing;

@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *vrButton;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UIProgressView *trackProgressView;


@end

@implementation DMTMD360PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //默认不能控制按钮，只有在视频文件加载成功后才可以进行播放，拖动，切换双屏
    self.playButton.alpha = 0;
    self.playButton.hidden = YES;
    self.slider.userInteractionEnabled = NO;
    self.vrButton.userInteractionEnabled = NO;
    
    //[_backButton addTarget:self action:@selector(closed) forControlEvents:UIControlEventTouchUpInside];
    
    @weakify(self);
    [[_backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self.player reset];
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
    
    [[self.vrButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        self.vrButton.selected = !self.vrButton.selected;
        if(self.vrButton.selected){
            [self.vrLibrary switchDisplayMode:MDModeDisplayGlass];
        }else{
            [self.vrLibrary switchDisplayMode:MDModeDisplayNormal];
        }
        
        [self toolBarHiddenWithTimeInterval:@(5.f)];
    }];
    
    [[self.playButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        //取消自动消失
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenToolview) object:nil];
        
        self.playButton.selected = !self.playButton.selected;
        if(self.playButton.selected){
            [self.player pause];
        }else{
            [self.player play];
        }
    }];
    
    _currentTimeLabel.text = @"00:00";
    
    //设置slider
//    _slider.minimumTrackTintColor = RGBCOLOR_HEX(0xd0121b);
//    _slider.maximumTrackTintColor = [UIColor clearColor];
//    _slider.backgroundColor = [UIColor clearColor];
    [_slider addTarget:self action:@selector(scrubbingDidStart) forControlEvents:UIControlEventTouchDown];
    [_slider addTarget:self action:@selector(scrubbingDidChange) forControlEvents:UIControlEventValueChanged];
    [_slider addTarget:self action:@selector(scrubbingDidEnd) forControlEvents:UIControlEventTouchUpOutside];
    [_slider addTarget:self action:@selector(scrubbingDidEnd) forControlEvents:UIControlEventTouchUpInside];
    //设置progressview
//    _trackProgressView.trackTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
//    _trackProgressView.progressTintColor = [UIColor blueColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)closed
{
    [self.player reset];
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void) initParams:(NSURL*)url title:(NSString *)title
{
    self.titleLabel.text = title;
    
    self.player = [[VIMVideoPlayer alloc] init];
    
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
    [self.player setPlayerItem:playerItem];
    self.player.delegate = self;
    
    /////////////////////////////////////////////////////// MDVRLibrary
    MDVRConfiguration* config = [MDVRLibrary createConfig];
    
    [config asVideo:playerItem];
    [config setContainer:self view:self.view];
    
    // optional
    [config projectionMode:MDModeProjectionSphere];
    [config displayMode:MDModeDisplayNormal];
    [config interactiveMode:MDModeInteractiveMotion];
    [config pinchEnabled:true];
    [config setDirectorFactory:[[CustomDirectorFactory alloc]init]];
    
    self.vrLibrary = [config build];
    /////////////////////////////////////////////////////// MDVRLibrary
    
}

- (void)tapMethod:(UITapGestureRecognizer *)tap
{
    if(!isShowToolBar)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenToolview) object:nil];
        [UIView animateWithDuration:0.5 animations:^{
            _topView.alpha = 0;
            _bottomView.alpha = 0;
            _playButton.alpha = 0;
            isShowToolBar = YES;
        }];
        
    }else
    {
        [self toolBarHiddenWithTimeInterval:@(5.f)];
        
        [UIView animateWithDuration:0.5 animations:^{
            _topView.alpha = 1;
            _bottomView.alpha = 1;
            _playButton.alpha = 1;
            isShowToolBar = NO;
        }];
    }
}

- (void)showToolView
{
    [UIView animateWithDuration:0.5 animations:^{
        _topView.alpha = 1;
        _bottomView.alpha = 1;
        _playButton.alpha = 1;
        isShowToolBar = NO;
    }];
}

- (void)hiddenToolview
{
    NSLog(@"hiddenToolview");
    [UIView animateWithDuration:0.5 animations:^{
        _topView.alpha = 0;
        _bottomView.alpha = 0;
        _playButton.alpha = 0;
        isShowToolBar = YES;
    }];
}

- (void)toolBarHiddenWithTimeInterval:(NSNumber *)time
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenToolview) object:nil];
    [self performSelector:@selector(hiddenToolview) withObject:nil afterDelay:[time doubleValue]];
}

#pragma mark - 计算缓冲进度
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    
    return result;
}

#pragma mark - VIMVideoPlayerDelegate
- (void)videoPlayerIsReadyToPlayVideo:(VIMVideoPlayer *)videoPlayer{
    //获取视频总时间
    NSUInteger dTotalSeconds = CMTimeGetSeconds(videoPlayer.player.currentItem.asset.duration);
//    NSUInteger dHours = floor(dTotalSeconds / 3600);
    NSUInteger dMinutes = floor(dTotalSeconds % 3600 / 60);
    NSUInteger dSeconds = floor(dTotalSeconds % 3600 % 60);
    NSString *videoDurationText = [NSString stringWithFormat:@"%02ld:%02lu",dMinutes, (unsigned long)dSeconds];
    
    self.totalTimeLabel.text = videoDurationText;
    
    //停止旋转
    [_activityView stopAnimating];
    //显示播放按钮
    self.playButton.hidden = NO;
    
    //添加手势事件
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod:)];
    [self.view addGestureRecognizer:tap];
    
    isShowToolBar = NO;
    
    [self toolBarHiddenWithTimeInterval:@(5.f)];
    
    self.slider.userInteractionEnabled = YES;
    self.vrButton.userInteractionEnabled = YES;
    NSLog(@"videoPlayerIsReadyToPlayVideo");
    
    [self.player play];
    
}
- (void)videoPlayerDidReachEnd:(VIMVideoPlayer *)videoPlayer{
    //播放结束 把播放按钮改为准备播放
    self.playButton.selected = YES;
    
}
- (void)videoPlayer:(VIMVideoPlayer *)videoPlayer timeDidChange:(CMTime)cmTime{
    
    if(self.isScrubbing == true){
        return;
    }
    CMTime playDuration = videoPlayer.player.currentItem.asset.duration;
    
    NSUInteger currentSeconds = CMTimeGetSeconds(cmTime);
//    NSUInteger dHours = floor(dTotalSeconds / 3600);
    NSUInteger dMinutes = floor(currentSeconds % 3600 / 60);
    NSUInteger dSeconds = floor(currentSeconds % 3600 % 60);
    NSString *videoDurationText = [NSString stringWithFormat:@"%02ld:%02lu",dMinutes, (unsigned long)dSeconds];
    
    //UI更新
    double duration = CMTimeGetSeconds(playDuration);
    double time = CMTimeGetSeconds(cmTime);
    
    //进度条更新
    [self.slider setValue:(time / duration)];
    //当前时间更新
    self.currentTimeLabel.text = videoDurationText;
    //缓冲进度更新
    NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
    [self.trackProgressView setProgress:timeInterval / duration animated:YES];
    
}
- (void)videoPlayer:(VIMVideoPlayer *)videoPlayer loadedTimeRangeDidChange:(float)duration{
    
}
- (void)videoPlayerPlaybackBufferEmpty:(VIMVideoPlayer *)videoPlayer{
    NSLog(@"%s",__FUNCTION__);
}
- (void)videoPlayerPlaybackLikelyToKeepUp:(VIMVideoPlayer *)videoPlayer{
    NSLog(@"%s",__FUNCTION__);
}
- (void)videoPlayer:(VIMVideoPlayer *)videoPlayer didFailWithError:(NSError *)error{
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark - delegate 视频拖放进度发生改变

// 开始拖动
- (void)scrubbingDidStart{
    self.isScrubbing = true;
    [self.player startScrubbing];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenToolview) object:nil];
}

// 结束拖动
- (void)scrubbingDidEnd{
    [self.player stopScrubbing];
    self.isScrubbing = false;
}
// 拖动值发生改变
- (void)scrubbingDidChange{

    if(self.isScrubbing == true){
        //获得总时间
        CMTime playDuration = self.player.player.currentItem.asset.duration;
        double duration = CMTimeGetSeconds(playDuration);
        
        float value = [_slider value];
        
        double time = duration * value;
        [self.player scrub:time];
    }
    
    [self toolBarHiddenWithTimeInterval:@(5.f)];
}

#pragma mark - 屏幕方向

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)shouldAutorotate{
    return YES;
}

#pragma mark - 状态栏
//设置样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

//设置是否隐藏
- (BOOL)prefersStatusBarHidden {
    //    [super prefersStatusBarHidden];
    return YES;
}

//设置隐藏动画
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

@end
